<template>
  <div class="p-2">
    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['wms:mall:add']">新增顶级菜单
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
          <right-toolbar :search="false" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="pd.loading" :data="pd.menuList" row-key="id" :default-expand-all="pd.isExpandAll" ref="treeTableRef">
        <el-table-column label="菜单名称" prop="name" />
        <el-table-column label="pc端图片预览" align="center" prop="url">
          <template #default="scope">
            <picture-preview
              v-if="scope.row.url != null"
              :width="100"
              :height="100"
              :src="scope.row.url"
              :preview-src-list="[scope.row.url]"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['wms:mall:add']">
              新增下级菜单
            </el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['wms:mall:edit']">
              修改
            </el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['demo:tree:remove']">删除
            </el-button>
          </template>
        </el-table-column>
        <el-table-column width="100px" label="排序" align="center" prop="sort" />
        <el-table-column width="100px" label="菜单状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
      <el-form ref="menuFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-form-item label="父菜单" prop="parentId">
          <el-tree-select v-model="pd.form.parentId" :data="pd.menuList"
                          :props="{ value: 'id', label: 'name', children: 'children'}"
                          value-key="id" check-strictly disabled />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="pd.form.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="pd.form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="pd.form.status" placeholder="请选择状态">
            <el-option v-for="dict in sys_status" :key="dict.value" :label="dict.name" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="产品图">
          <PictureUpload :limit=1 :show-list="true" :is-menu="true" :id-list="pd.picIdList" @ok="pcIcon"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<!-- 商城菜单 -->
<script setup name="wmsMallMenu" lang="ts">
import {mallMenu, listMenu, addMenu, updateMenu, deleteMenu} from "@/views/mall/api";
import PictureUpload from "@/views/system/oss/pictureUpload.vue";
import PicturePreview from "@/views/system/oss/picturePreview.vue";

const {proxy} = getCurrentInstance() as ComponentInternalInstance;
const { sys_status } = toRefs<any>(proxy?.useDict('sys_status' ));

const menuFormRef = ref<ElFormInstance>();
const treeTableRef = ref<ElTableInstance>()

const pd = reactive({
  menuList: <mallMenu[]>([]),
  picIdList: <any>[],
  isExpandAll: false,
  ids: <number[]>[],
  loading: true,
  buttonLoading: false,
  showSearch: true,
  total: 0,
  lineTotal: 0,
  form: <mallMenu>{},
  dialog: <DialogOption>{
    visible: false,
    title: ''
  },
  queryParams: <mallMenu>{
    pageNum: 1,
    pageSize: 10
  },
  rules: <ElFormRules>{
    name: [{required: true, message: "单据类别不能为空", trigger: "change"}],
    status: [{required: true, message: "状态不能为空", trigger: "change"}]
  }
});

/** 查询菜单列表 */
async function getList() {
  pd.loading = true;
  const res = await listMenu();
  pd.menuList = res.rows;
  pd.menuList = proxy?.handleTree<mallMenu>(res.rows, "id", "parentId", "children") as mallMenu[];
  pd.loading = false;
}
// 表单重置
function reset() {
  pd.form = {};
  pd.picIdList = [];
  menuFormRef.value?.resetFields();
}
/** 新增按钮操作 */
function handleAdd(row?: mallMenu) {
  reset();
  if (row && row.id) {
    pd.dialog.title = "新增下级菜单";
    pd.form.parentId = row.id;
  }else{
    pd.dialog.title = "新增顶级菜单";
    pd.form.parentId = 0;
  }
  pd.form.status = '0';
  pd.dialog.visible = true;
}

/** 修改按钮操作 */
async function handleUpdate(row: mallMenu) {
  reset();
  Object.assign(pd.form, row);
  pd.picIdList.push(pd.form.iconPc);
  pd.dialog.visible = true;
  pd.dialog.title = "修改菜单";
}

/** 删除按钮操作 */
async function handleDelete(row: mallMenu) {
  if (row.id){
  if (row.children){
    await proxy?.$modal.confirm('是否确认删除菜单:"' + row.name + '"及其子菜单？');
    pd.ids = getIds(row.children);
  }else{
    await proxy?.$modal.confirm('是否确认删除菜单:"' + row.name + '"？');
  }
    pd.ids.push(row.id);
  }
  pd.loading = true;
  await deleteMenu(pd.ids).then(()=>{
    getList();
    proxy?.$modal.msgSuccess("删除成功");
  }).finally(() => pd.loading = false);
}

function getIds(list: any){
  let ids: number[] = [];
  list.forEach((item: { id: number; children: any; })=>{
    ids.push(item.id);
    if (item.children){
      ids = ids.concat(getIds(item.children));
    }
  })
  return ids;
}

/** 展开/折叠操作 */
function handleToggleExpandAll() {
  pd.isExpandAll = !pd.isExpandAll;
  toggleExpandAll(pd.menuList, pd.isExpandAll)
}

/** 展开/折叠操作 */
function toggleExpandAll(data: mallMenu[], status: boolean) {
  data.forEach((item) => {
    treeTableRef.value?.toggleRowExpansion(item, status)
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status)
  })
}

/** 提交按钮 */
function submitForm() {
  menuFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.dialog.title === "修改菜单") {
        await updateMenu(pd.form).finally(() => pd.buttonLoading = false);
      } else {
        await addMenu(pd.form).finally(() => pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

// 取消按钮
function cancel() {
  reset();
  pd.dialog.visible = false;
}

//更新图片
function pcIcon(list: any) {
  if (list == null){
    pd.form.iconPc = -1;
    pd.picIdList = [];
  }else{
    list.forEach((element: any) => {
      pd.form.iconPc = element.ossId;
      return;
    });
  }
}


onMounted(() => {
  getList();
});
</script>

<style lang="scss">
</style>
